package template.security;

import java.io.IOException;

import java.security.MessageDigest;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public final class Algorithm {
	
	/**
	 * Triple DES
	 */
	private static final String DESEDE = "DESede";
	
	private static final BASE64Encoder encoder = new BASE64Encoder();

	private static final BASE64Decoder decoder = new BASE64Decoder();

	/**
	 * Base64编码
	 * 
	 * @param encoded
	 * @return
	 */
	final public static String base64Decode(String encoded) {
		byte[] bt = null;
		try {
			bt = decoder.decodeBuffer(encoded);
		} catch (IOException ex) {
			return "";
		}
		return new String(bt);
	}

	/**
	 * Base64解码
	 * 
	 * @param plainText
	 * @return
	 */
	final public static String base64Encode(String plainText) {
		try {
			return encoder.encode(plainText.getBytes());
		} catch (Exception e) {
			return "";
		}
	}

	/**
	 * SHA-1加密算法
	 * 
	 * @param string
	 * @return
	 */
	public static String sha1Encrypt(String string) {
		try {

			MessageDigest alg = MessageDigest.getInstance("SHA-1");
			alg.update(string.getBytes());
			byte[] userPwd = alg.digest();
			return bytes2Hex(userPwd);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * MD5加密算法
	 * 
	 * @param string
	 * @return
	 */
	public static String md5Encrypt(String string) {
		try {
			MessageDigest alg = MessageDigest.getInstance("MD5");
			alg.update(string.getBytes());
			byte[] userPwd = alg.digest();
			return bytes2Hex(userPwd);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * SHA-256加密算法
	 * 
	 * @param string
	 * @return
	 */
	public static String sha256Encrypt(String string) {
		try {
			MessageDigest alg = MessageDigest.getInstance("SHA-256");
			alg.update(string.getBytes());
			byte[] userPwd = alg.digest();
			return bytes2Hex(userPwd);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
	
}